import React, { useRef, useEffect } from 'react';
import { useTranslation } from 'react-i18next';
import { ImageCollectionItem as ImageCollectionItemType } from '../../../hooks/useImageCollection';
import ImageCollectionItem from './ImageCollectionItem';

interface ImageCollectionGridProps {
  data: ImageCollectionItemType[];
  loading: boolean;
  loadingMore: boolean;
  error: string | null;
  hasMore: boolean;
  onItemClick?: (item: ImageCollectionItemType) => void;
  onLoadMore?: () => void;
}

/**
 * 图片收藏网格组件
 */
const ImageCollectionGrid: React.FC<ImageCollectionGridProps> = ({
  data,
  loading,
  loadingMore,
  error,
  hasMore,
  onItemClick,
  onLoadMore
}) => {
  const { t } = useTranslation();
  const lastItemRef = useRef<HTMLDivElement>(null);

  // 使用 Intersection Observer 监听最后一张图片
  useEffect(() => {
    if (!lastItemRef.current || data.length === 0 || !hasMore || loadingMore) return;

    const observer = new IntersectionObserver(
      (entries) => {
        entries.forEach((entry) => {
          if (entry.isIntersecting && hasMore && !loadingMore && onLoadMore) {
            // console.log('🔄 最后一张图片进入视口，开始加载更多数据...');
            onLoadMore();
          }
        });
      },
      {
        threshold: 0.1, // 当最后一张图片的10%进入视口时触发
        rootMargin: '0px 0px 100px 0px' // 提前100px触发，提供更好的用户体验
      }
    );

    observer.observe(lastItemRef.current);

    return () => {
      observer.disconnect();
    };
  }, [data.length, hasMore, loadingMore, onLoadMore]);

  // 加载状态
  if (loading) {
    return (
      <div className="flex items-center justify-center min-h-64 sm:min-h-96 text-gray-400">
        <div className="text-center">
          <i className="fas fa-spinner fa-spin text-2xl sm:text-3xl mb-3 sm:mb-4" />
          <div className="text-sm sm:text-base">{t('imageCollection.loading')}</div>
        </div>
      </div>
    );
  }

  // 错误状态
  if (error) {
    return (
      <div className="flex items-center justify-center min-h-64 sm:min-h-96 text-red-400">
        <div className="text-center px-4">
          <i className="fas fa-exclamation-circle text-2xl sm:text-3xl mb-3 sm:mb-4" />
          <div className="text-sm sm:text-base">{error}</div>
        </div>
      </div>
    );
  }

  // 无数据状态
  if (!data || data.length === 0) {
    return (
      <div className="flex items-center justify-center min-h-64 sm:min-h-96 text-gray-400">
        <div className="text-center">
          <i className="fas fa-image text-2xl sm:text-3xl mb-3 sm:mb-4" />
          <div className="text-sm sm:text-base">{t('imageCollection.noImages')}</div>
        </div>
      </div>
    );
  }

  return (
    <div className=" sm:p-4 md:p-6 mt-6">
      {/* 响应式网格布局 */}
      <div className="grid grid-cols-2 sm:grid-cols-2 md:grid-cols-3 lg:grid-cols-4 xl:grid-cols-5 gap-3 sm:gap-4">
        {data.map((item, index) => (
          <div
            key={`${item.username}-${item.created_at}-${index}`}
            ref={index === data.length - 1 ? lastItemRef : null} // 给最后一个元素添加ref
          >
            <ImageCollectionItem
              item={item}
              onClick={onItemClick}
            />
          </div>
        ))}
      </div>

      {/* 加载更多状态 */}
      {loadingMore && (
        <div className="flex items-center justify-center py-8 text-gray-400">
          <div className="text-center">
            <i className="fas fa-spinner fa-spin text-xl mb-2" />
            <div className="text-sm">{t('imageCollection.loadingMore')}</div>
          </div>
        </div>
      )}

      {/* 没有更多数据提示 */}
      {!hasMore && data.length > 0 && (
        <div className="flex items-center justify-center py-8 text-gray-400">
          <div className="text-center">
            <i className="fas fa-check-circle text-xl mb-2" />
            <div className="text-sm">{t('imageCollection.noMoreImages')}</div>
          </div>
        </div>
      )}
    </div>
  );
};

export default ImageCollectionGrid;